package com.bqnxzz.ywiigame.nativeInterface;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

import com.okgame.sdk.OkGame;
import com.bqnxzz.ywiigame.MainActivity;
import com.bqnxzz.ywiigame.util.HotUpdateUtil;

import static android.content.Context.BATTERY_SERVICE;

public class XYNativeJSInterface {
    private static final String TAG = "H5_XYNativeJSInterface";

    @JavascriptInterface
    public void exitApp() {
        Log.d(TAG, "exitApp");
        System.exit(0);
    }

    @JavascriptInterface
    public void closePreloading() {
        Log.d(TAG, "closePreloading");
        MainActivity.self.runOnUiThread(() -> MainActivity.self.closePreloading());
    }

    @SuppressLint("LongLogTag")
    @JavascriptInterface
    public void initApp() {
        Log.d(TAG, "initApp");
        MainActivity.self.runOnUiThread(() -> {
            MainActivity.self.getSystemLanguage();
            String localStorge = "";
            try {
                File file = new File(HotUpdateUtil.getLocalGamesPath() + "localStorge.info");
                localStorge = HotUpdateUtil.readFile(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            MainActivity.self.hallView.callJS(JSCall.fullCache, localStorge);
            if (MainActivity.self.gameView != null) {
                MainActivity.self.gameView.callJS(JSCall.fullCache, localStorge);
            }
        });
    }

    @JavascriptInterface
    public void startLoadGame(final String basicConfig) {
        Log.d(TAG, "startLoadGame " + basicConfig);
        MainActivity.self.runOnUiThread(() -> MainActivity.self.startLoadGame(basicConfig));
    }

    @JavascriptInterface
    public void sendMsgToGame(final String data) {
        Log.d(TAG, "sendMsgToGame " + data);
        MainActivity.self.runOnUiThread(() -> MainActivity.self.gameView.callJS(JSCall.recieveGlobalEvent, data));
    }

    @JavascriptInterface
    public void sendMsgToHall(final String data) {
        Log.d(TAG, "sendMsgToHall " + data);
        MainActivity.self.runOnUiThread(() -> MainActivity.self.hallView.callJS(JSCall.recieveGlobalEvent, data));
    }

    @JavascriptInterface
    public void showGame() {
        Log.d(TAG, "showGame ");
        MainActivity.self.runOnUiThread(() -> MainActivity.self.showGame());
    }

    @JavascriptInterface
    public void unloadGame() {
        Log.d(TAG, "unloadGame ");
        MainActivity.self.runOnUiThread(() -> MainActivity.self.unloadGame());
    }

    @JavascriptInterface
    public String getShareedParamFromHall() {
        Log.d(TAG, "getShareedParamFromHall " + MainActivity.self.gameView.initJsData);
        return MainActivity.self.gameView.initJsData;
    }

    @SuppressLint("HardwareIds")
    @JavascriptInterface
    public String getUdid() {
        return OkGame.getDeviceId(MainActivity.self);
    }

    @JavascriptInterface
    public void updateFullCache(String data) {
        Log.d(TAG, "updateFullCache " + data);
        FileOutputStream o;
        try {
            o = new FileOutputStream(HotUpdateUtil.getLocalGamesPath() + "localStorge.info");
            o.write(data.getBytes("UTF-8"));
            o.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        MainActivity.self.runOnUiThread(() -> {
            MainActivity.self.hallView.callJS(JSCall.fullCache, data);
            if (MainActivity.self.gameView != null) {
                MainActivity.self.gameView.callJS(JSCall.fullCache, data);
            }
        });
    }

    @JavascriptInterface
    public void clearCache() {
        MainActivity.self.hallView.clearCache();
        if (MainActivity.self.gameView != null) {
            MainActivity.self.gameView.clearCache();
        }
    }

    @JavascriptInterface
    public int getPhonePower() {
        Log.d(TAG, "getPhonePower ");
        int power = 80;
        BatteryManager batterymanager = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            batterymanager = (BatteryManager) MainActivity.self.getSystemService(BATTERY_SERVICE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            power = batterymanager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        }

        if (power <= 0) {
            power = 100;
        }

        return power;
    }

    @JavascriptInterface
    public void setPhoneStatusBar(String data) {
        Log.d(TAG, "setPhoneStatusBar ");
    }

    @JavascriptInterface
    public String getAppInfo() {
        Log.d(TAG, "getAppInfo ");
        String data = "";
        try {
            data = HotUpdateUtil.readFile(new File(HotUpdateUtil.getAppInfoFileName()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }

    @JavascriptInterface
    public void downloadGamePackage(final String gameId) {
        Log.d(TAG, "downloadGamePackage ");
    }

    @JavascriptInterface
    public void layoutWithKeyboard(final String offsetYStr) {
        Log.d(TAG, "layoutWithKeyboard " + offsetYStr);
        MainActivity.self.runOnUiThread(() -> MainActivity.self.setLayoutWithKeyboard(Double.valueOf(offsetYStr).intValue()));
    }

    @JavascriptInterface
    public void savePic(final String base64DataStr) {
        // 1.去掉base64中的前缀
        String base64Str = base64DataStr.substring(base64DataStr.indexOf(",") + 1, base64DataStr.length());
        // 获取手机相册的路径地址
        String galleryPath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;
        //创建文件来保存，第二个参数是文件名称，可以根据自己来命名
        File file = new File(galleryPath, System.currentTimeMillis() + ".png");
        String fileName = file.toString();
        // 3. 解析保存图片
        byte[] data = Base64.decode(base64Str, Base64.DEFAULT);

        for (int i = 0; i < data.length; i++) {
            if (data[i] < 0) {
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(fileName);
            os.write(data);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //通知相册更新
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);

            MainActivity.self.sendBroadcast(intent);
        }
    }

    @JavascriptInterface
    public void takePhoto() {
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//调用android自带的照相机
//        // photoUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//        MainActivity.self.startActivity(intent);
    }

    @JavascriptInterface
    public void copyText(final String text) {
        copy(text);
    }

    @JavascriptInterface
    public void copyAndOpenWeixin(final String weixin) {
        copy(weixin);
        if (isInstall("com.tencent.mm")) {
            final String weixinUrl = "weixin://";
            MainActivity.self.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(weixinUrl)));
        } else {
            Toast toast = Toast.makeText(MainActivity.self, "检查到您手机没有安装微信，请安装后使用该功能", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    }

    @JavascriptInterface
    public void copyAndOpenQQ(final String qq) {
        copy(qq);
        if (isInstall("com.tencent.mobileqq")) {
            final String qqUrl = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;
            MainActivity.self.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qqUrl)));
        } else {
            Toast toast = Toast.makeText(MainActivity.self, "检查到您手机没有安装QQ，请安装后使用该功能", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    }

    @JavascriptInterface
    public void setLoginSuccessUrl(final String url) {
        Log.d(TAG, "loginSuccessUrl " + url);
        HotUpdateUtil.appinfo.put("loginSuccessUrl", url);
        HotUpdateUtil.writeAppInfoToFile();
    }

    @JavascriptInterface
    public void openWindow(final String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        MainActivity.self.startActivity(intent);
    }

    @JavascriptInterface
    public void visitorLoginORIGIN() {
        MainActivity.self.visitorLoginORIGIN();
    }

    @JavascriptInterface
    public void facebookLoginORIGIN() {
        MainActivity.self.facebookLoginORIGIN();
    }

    @JavascriptInterface
    public void googleLoginORIGIN() {
        MainActivity.self.googleLoginORIGIN();
    }

    @JavascriptInterface
    public void facebookShareORIGIN(String jsonStr) {
        MainActivity.self.facebookShareORIGIN(jsonStr);
    }

    @JavascriptInterface
    public void whatsappShareORIGIN(String jsonStr) {
        MainActivity.self.whatsappShareORIGIN(jsonStr);
    }

    @JavascriptInterface
    public void nativeShareORIGIN(String jsonStr) {
        MainActivity.self.nativeShareORIGIN(jsonStr);
    }

    @JavascriptInterface
    public void googlePayOrigin(String jsonStr) {
        MainActivity.self.googlePayOrigin(jsonStr);
    }

    @JavascriptInterface
    public void getInviteLink(String jsonStr) {
        MainActivity.self.getInviteLink(jsonStr);
    }

    @JavascriptInterface
    public void trackEventLogin(String jsonStr) {
        MainActivity.self.trackEventLogin(jsonStr);
    }

    @JavascriptInterface
    public void trackEventRegister(String jsonStr) {
        MainActivity.self.trackEventRegister(jsonStr);
    }

    @JavascriptInterface
    public void trackEventBuy(String jsonStr) {
        MainActivity.self.trackEventBuy(jsonStr);
    }

    @JavascriptInterface
    public void trackEvent(String jsonStr) {
        MainActivity.self.trackEvent(jsonStr);
    }

    private boolean isInstall(String packageName) {
        final PackageManager packageManager = MainActivity.self.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                //通过遍历应用所有包名进行判断
                if (pn.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    private void copy(String copyStr) {
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) MainActivity.self.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", copyStr);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
        } catch (Exception e) {
        }
    }

}
